import * as zrender from "zrender";

import {
  barHeight,
  barMargin,
  setCurrentGroup,
  unitWidth,
} from "../../config";

import { createLeftArrowRect, createRightArrowRect } from "./create-arrow";
import { getLeftHandleBar, getRightHandleBar } from "./handle-bar";
import { addTaskTexts } from "./task-text";
import { getTaskBarMoveLine } from "./move-line";

/**
 * 绘制任务条
 * @param {Object} zr ZRender实例
 * @param {Array} tasks 任务数组
 * @param {Object} chartState 图表状态对象
 * @param {Function} redrawChart 重绘图表函数
 * @param {Object} currentGroup 当前操作组
 * @returns {number} 绘制的任务条数量
 */
export function drawTaskBars(
  zr: any,
  tasks: Task[],
  chartState: ChartState,
  redrawChart: RedrawChartFunction,
  currentGroup: any
) {
  let drawTaskBar = 0;
  const boundingLeft = Math.floor(chartState.lastScrollX / unitWidth);
  const boundingRight = Math.floor((chartState.lastScrollX + chartState.canvasWidth) / unitWidth);

  tasks.forEach(function (task, index) {
    if (!task?.name) return;

    // 性能优化：在视口外跳过
    if (index > Math.floor((chartState.canvasHeight - chartState.chartStartY) / (barHeight + barMargin))) return;

    const showLeftArrow = task.start <= boundingLeft;
    const showRightArrow = (task.start + task.duration) > boundingRight;

    // 计算位置和尺寸
    const x = chartState.chartStartX + task.start * unitWidth;
    const y = chartState.chartStartY + (barHeight + barMargin) * index;
    const width = task.duration * unitWidth;
    const taskBarRect = {
      width,
      height: barHeight
    };

    // 创建左右箭头
    const leftArrow = createLeftArrowRect(x, y, task, taskBarRect, showLeftArrow, boundingLeft, function () {
      redrawChart(true, (task.start - 3) * unitWidth, 0);
    });
    const rightArrow = createRightArrowRect(x, y, task, unitWidth, chartState.lastScrollX, chartState.canvasWidth, taskBarRect, showRightArrow, boundingRight, function () {
      redrawChart(true, (task.start + task.duration + 3) * unitWidth - chartState.canvasWidth, 0);
    });
    leftArrow && zr.add(leftArrow);
    rightArrow && zr.add(rightArrow);

    if (task.start > boundingRight || (task.start + task.duration) < boundingLeft) return;
    drawTaskBar++;

    // 创建任务组
    const group = createTaskGroup(x, y, width, task, index, chartState, tasks, redrawChart, currentGroup, zr);
    zr.add(group);
  });

  return drawTaskBar;
}

/**
 * 创建任务组
 * @param {number} x X坐标
 * @param {number} y Y坐标
 * @param {number} width 宽度
 * @param {Object} task 任务对象
 * @param {number} index 任务索引
 * @param {Object} chartState 图表状态对象
 * @param {Array} tasks 任务数组
 * @param {Function} redrawChart 重绘图表函数
 * @param {Object} currentGroup 当前操作组
 * @param {Object} zr ZRender实例
 * @returns {Object} 任务组
 */
function createTaskGroup(
  x: number,
  y: number,
  width: number,
  task: Task,
  index: number,
  chartState: ChartState,
  tasks: Task[],
  redrawChart: RedrawChartFunction,
  currentGroup: any,
  zr: any
) {
  const group = new zrender.Group({
    x,
    y,
    draggable: true
  });

  // 设置组的索引
  (group as any).index = index;

  // 创建任务矩形
  const rect = new zrender.Rect({
    shape: {
      x: 0,
      y: 0,
      width: width,
      height: barHeight,
      r: 6
    },
    style: {
      fill: task.fillColor
    },
    cursor: 'move'
  });
  group.add(rect);

  // 创建调整大小的手柄
  const w = 6;
  const box = rect.getBoundingRect();

  const leftBar = getLeftHandleBar(w, box, { width, height: barHeight }, redrawChart, tasks, index);
  (leftBar as any).taskBar = rect;
  group.add(leftBar);

  const rightBar = getRightHandleBar(w, box, { width, height: barHeight }, redrawChart, tasks, index);
  (rightBar as any).taskBar = rect;
  group.add(rightBar);

  // 添加文字元素
  addTaskTexts(group, task, width);

  // 设置事件处理
  setupTaskEvents(group, rect, task, index, chartState, tasks, redrawChart, currentGroup, zr);

  return group;
}

/**
 * 设置任务事件
 * @param {Object} group 任务组
 * @param {Object} rect 任务矩形
 * @param {Object} task 任务对象
 * @param {number} index 任务索引
 * @param {Object} chartState 图表状态对象
 * @param {Array} tasks 任务数组
 * @param {Function} redrawChart 重绘图表函数
 * @param {Object} currentGroup 当前操作组
 * @param {Object} zr ZRender实例
 */
function setupTaskEvents(group: any, rect: any, task: Task, index: number, chartState: ChartState, tasks: Task[], redrawChart: RedrawChartFunction, currentGroup: any, zr: any) {
  // 使用闭包来跟踪状态，避免使用 this
  let isDragging = false;
  let isResizing = false;
  let isContextMenu = false;

  // 提供状态更新函数给子组件使用
  const updateResizingState = (resizing: boolean) => {
    isResizing = resizing;
  };

  // 鼠标悬停事件
  group.on("mouseover", () => {
    if (isDragging) return;
    rect.attr("style", { fill: zrender.color.lift(task.fillColor, 0.3) });
  });

  group.on("mouseout", () => {
    if (isDragging || isResizing) return;
    rect.attr("style", { fill: task.fillColor });
  });

  // 拖拽逻辑
  let dragStartX = 0;
  let lastPosY: number | null = null;
  let lastBottomLine: any = null;

  group.on("dragstart", (e: any) => {
    if (isResizing) return;
    isDragging = true;
    dragStartX = e.event.zrX;
    setCurrentGroup(group);
  });

  group.on("drag", (e: any) => {
    if (isResizing) return;
    const y = e.event.zrY - chartState.chartStartY;
    const posY = Math.floor(y / (barHeight + barMargin));

    if (lastPosY !== posY) {
      lastPosY = posY;
      zr.remove(lastBottomLine);
      // 临时注释掉未定义的函数调用
      const bottomLine = getTaskBarMoveLine(chartState.chartStartX, chartState.chartStartY, chartState.lastScrollX, chartState.timeScaleWidth, posY, tasks);
      lastBottomLine = bottomLine;
      bottomLine && zr.add(bottomLine);
      zr.refresh();
    }
  });

  group.on("dragend", (e: any) => {
    if (isContextMenu) {
      isContextMenu = false;
      return;
    }

    isDragging = false;

    if (isResizing) {
      isResizing = false;
      return;
    }

    const deltaX = e.event.zrX - dragStartX;
    const dir = deltaX < 0 ? -1 : 1;
    const delta = Math.abs(deltaX);
    const mod = delta % unitWidth;
    const offsetX = dir * (Math.floor(delta / unitWidth) + Math.floor(mod / (unitWidth / 2)));

    const y = e.event.zrY - chartState.chartStartY;
    const posY = Math.floor(y / (barHeight + barMargin));
    const offsetY = posY - index;

    task.start += offsetX;

    if (lastBottomLine && posY !== index) {
      // 删除当前项目
      tasks.splice(index, 1);
      // 移动当前项目到目标位置
      tasks.splice(posY > index ? posY - 1 : posY, 0, { ...task });
    }

    if (offsetX || offsetY) {
      // 状态已更新，可以在这里添加其他逻辑
    }

    setCurrentGroup(null);
    redrawChart(true);
  });

  // 设置子元素层级
  group.eachChild((child: any) => {
    child.attr({
      z: 10
    });
  });

  // 将状态更新函数添加到组对象上，供子组件使用
  (group as any).updateResizingState = updateResizingState;

  // // 双击事件
  // group.on("dblclick", () => {
  //   Popup.show({
  //     currentIndex: index
  //   });
  // });

  // 右键菜单事件
  // group.on("contextmenu", (e) => {
  //   isContextMenu = true;
  //   e.event.preventDefault();
  //   const { zrX: x, zrY: y } = e.event;
  //   ContextMenu.show({
  //     currentIndex: index,
  //     position: {
  //       x,
  //       y
  //     }
  //   });
  // });
} 